<?php
/**
 * @copyright 2011
 * @version $Id$
 * @access public
 * @author Oriotiori

 */

Class Default_Model_Users  extends Zend_Db_Table_Abstract{

	protected $_name = 'users';


	/**
	 * @param mixed $To: objeto con los datos de la busqueda.
	 * @return array $data
	 */
	function getPaises()
	{
		$TO = new Default_Model_TO_Paises();

		try{
			$sql=$this->getAdapter()
			->select()
			->from(TABLE_PREFIX.'paises');

			$data0 = $this->getAdapter()->fetchAll($sql);
			$rowCount = count($data0);

			if ($rowCount > 0){
				foreach($data0 as $dt){
					$TO->setId($dt['id']);
					$TO->setPais($dt['pais']);
					$TO->add();
				}
				$data = $TO->getAllData();
				return $data;
			}

			return null;
		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
	}


	/**
	 * @param mixed $To: objeto con los datos de la busqueda.
	 * @return array $data
	 */
	function getestadosbyidpais($id=0)
	{
		$TO = new Default_Model_TO_Estados();

		try{
			$sql=$this->getAdapter()
			->select()
			->from(TABLE_PREFIX.'estados')
			->where('relacion=?', $id);

			$data0 = $this->getAdapter()->fetchAll($sql);
			$rowCount = count($data0);

			if ($rowCount > 0){
				foreach($data0 as $dt){
					$TO->setId($dt['id']);
					$TO->setEstado($dt['estado']);
					$TO->add();
				}
				$data = $TO->getAllData();
				return $data;
			}

			return null;
		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
	}



	/**
	 * Agrega nuevo producto
	 * @param Array $to
	 * @return int $lastId
	 */
	public function addUser($to)
	{
		try{
			$data = array(
						'Email'     		=> $to['Email'],
						'Password'  		=> md5($to['Passwd']),
						'Username'  		=> $to['Username'],
						'Role'		  		=> $to['Role'],
						'Creation_Date'		=> new Zend_Db_Expr('now()')
			);
			$res = $this->getAdapter()->insert(TABLE_PREFIX.'users' ,$data);
			$lastId= $this->getAdapter()->lastInsertId();
			if($lastId > 0){
				$to['User_Id']=$lastId;
				$this->addUserInformationByIdUser($to);
				$this->addBillingInformationByIdUser($to);
				$this->deleteAllAccessPermissionsByIdUser($to);
				$this->addAccessPermissionsByIdUser($to);
				$this->sendEmailNewUser($to);
				return $lastId;
			}
			return false;

		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
		return false;
	}


	/**
	 * Actualiza Producto
	 * @param Array $to
	 * @return int $lastId
		*/
	public function updateUserById($to)
	{
			
		try{
			$data = array('Email'	=> $to['Email']);
			$where[]="Id=". $to['User_Id'];
			$res = $this->getAdapter()->update(TABLE_PREFIX.'users' ,$data, $where);

			$this->updateUserInformationByIdUser($to);
			$this->updateBillingInformationByIdUser($to);
			return true;

		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
		return false;
	}


	/**
	 * agregamos permisos  al nuevo usr
	 * */
	public function addAccessPermissionsByIdUser($to){
		$res = $this->getAdapter()->insert(TABLE_PREFIX.'useraccess' ,array('User_Id' => $to['User_Id'], 'Module_Id' => 4));
		$res = $this->getAdapter()->insert(TABLE_PREFIX.'useraccess' ,array('User_Id' => $to['User_Id'], 'Module_Id' => 5));
		
	}
	
	public function deleteAllAccessPermissionsByIdUser($to){
	
		$res = $this->getAdapter()->delete(TABLE_PREFIX.'useraccess' ,"User_Id=".$to['User_Id']);
	}
	
	/**
		* @param Array $to
		* @return int $lastId
		*/
	public function addUserInformationByIdUser($to)
	{
		try{
			$data = array(
				'Birthdate'		=> (!empty($to['Birthdate'])) ? $to['Birthdate'] : new Zend_Db_Expr('null'),
				'Newsletter'	=> (int)$to['Newsletter'],
				'Phone_Office'	=> (!empty($to['Officephone'])) ? $to['Officephone'] : new Zend_Db_Expr('null'),
				'User_Id'	=> (!empty($to['User_Id'])) ? $to['User_Id'] : 0
			);

			$res = $this->getAdapter()->insert(TABLE_PREFIX.'user_information' ,$data);
			$lastId= $this->getAdapter()->lastInsertId();
			return $lastId;

		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
		return false;
	}


	/**
	 * @param Array $to
	 * @return int $lastId
	 */
	public function updateUserInformationByIdUser($to)
	{
		try{

			$sql=$this->getAdapter()
					->select()
					->from(array('ui' => TABLE_PREFIX.'user_information'), array('ui.Id'))
					->where("ui.User_Id=".$to['User_Id']);
			$res = $this->getAdapter()->fetchAll($sql);
			$rowCount=count($res);

			if($rowCount == 0){
				$this->addUserInformationByIdUser($to);
			}
			else{
				$data = array(
						'Birthdate'		=> (!empty($to['Birthdate'])) ? $to['Birthdate'] : new Zend_Db_Expr('null'),
						'Newsletter'	=> (int)$to['Newsletter'],
						'Phone_Office'	=> (!empty($to['Officephone'])) ? $to['Officephone'] : new Zend_Db_Expr('null')
				);
				$where="User_Id=".$to['User_Id'];
				$res = $this->getAdapter()->update(TABLE_PREFIX.'user_information' ,$data, $where);
			}
			return true;

		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
		return false;
	}

	/**
		* @param Array $to
		* @return int $lastId
		*/
	public function addBillingInformationByIdUser($to)
	{
		try{
			$data = array(
						'Name'     		=> (!empty($to['Name'])) ? $to['Name'] : new Zend_Db_Expr('null'),
						'Surnames'		=> (!empty($to['Surnames'])) ? $to['Surnames'] : new Zend_Db_Expr('null'),
						'Phone'			=> (!empty($to['Phone'])) ? $to['Phone'] : new Zend_Db_Expr('null'),
						'User_Id'   => (int)$to['User_Id'],
						'Address1'	=> (!empty($to['Address1'])) ? $to['Address1'] : new Zend_Db_Expr('null'),
						'Address2'	=> (!empty($to['Address2'])) ? $to['Address2'] : new Zend_Db_Expr('null'),
						'Col'		=> (!empty($to['Col'])) ? $to['Col'] : new Zend_Db_Expr('null'),
						'NumExt'	=> (!empty($to['NumExt'])) ? $to['NumExt'] : new Zend_Db_Expr('null'),
						'CP'		=> (!empty($to['CP'])) ? $to['CP'] : new Zend_Db_Expr('null'),
						'City'		=> (!empty($to['City'])) ? $to['City'] : new Zend_Db_Expr('null'),
						'State_Id'	=> (int)$to['State'],
						'Country_Id'=> (int)$to['Country'],
						'Used'		=> 	1,
						'RFC'		=> (!empty($to['RFC'])) ? $to['RFC'] : new Zend_Db_Expr('null')
			);

			$res = $this->getAdapter()->insert(TABLE_PREFIX.'billing_information' ,$data);

			return true;

		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
		return false;
	}


	/**
		* @param Array $to
		* @return int $lastId
		*/
	public function updateBillingInformationByIdUser($to)
	{
		try{
			$data = array(
						'Name'     	=> (!empty($to['Name'])) ? $to['Name'] : new Zend_Db_Expr('null'),
						'Surnames'	=> (!empty($to['Surnames'])) ? $to['Surnames'] : new Zend_Db_Expr('null'),
						'Phone'		=> (!empty($to['Phone'])) ? $to['Phone'] : new Zend_Db_Expr('null'),
						'Address1'	=> (!empty($to['Address1'])) ? $to['Address1'] : new Zend_Db_Expr('null'),
						'Address2'	=> (!empty($to['Address2'])) ? $to['Address2'] : new Zend_Db_Expr('null'),
						'Col'		=> (!empty($to['Col'])) ? $to['Col'] : new Zend_Db_Expr('null'),
						'NumExt'	=> (!empty($to['NumExt'])) ? $to['NumExt'] : new Zend_Db_Expr('null'),
						'CP'		=> (!empty($to['CP'])) ? $to['CP'] : new Zend_Db_Expr('null'),
						'City'		=> (!empty($to['City'])) ? $to['City'] : new Zend_Db_Expr('null'),
						'State_Id'	=> (int)$to['State'],
						'Country_Id'=> (int)$to['Country'],
						'RFC'		=> (!empty($to['RFC'])) ? $to['RFC'] : new Zend_Db_Expr('null')
			);

			$where[]="User_Id=".$to['User_Id'];
			$res = $this->getAdapter()->update(TABLE_PREFIX.'billing_information' ,$data, $where);
			return true;

		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
		return false;
	}



	public function setNoDefaultBillingInformation($to){
		try{
			$data = array('Used'=> 0);
			$res = $this->getAdapter()->update(TABLE_PREFIX.'billing_information' ,$data, "User_Id=".$to['User_Id']);
			return true;
		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
		return false;
	}
	
	
	public function setDefaultBillingInformation($to){
		try{				
			$data = array('Used'=> 1);
			$where[]="User_Id=".$to['User_Id'];
			$where[]="Id=".$to['AddressDefault'];
			$res = $this->getAdapter()->update(TABLE_PREFIX.'billing_information' ,$data, $where);
			return $true;
		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
		return false;
	}
	/*****
	 * Metodo para enviar email
	* **/

	public function sendEmailNewUser($to){

		$facadeCompany= new Admin_Model_Facade_Company();
		$company=$facadeCompany->getCompanyInformation(1);
		
		
		ob_start();
		include_once(EMAILS_PATH.DIAG_PATH."newuser.tpl.inc.php");
		$email_msg = ob_get_contents();
		ob_end_clean();

		$msg= str_replace(
						array('{Sr}', '{Name}', '{Surnames}', '{Url_Site}', '{Information_Email}', '{Owner_Name}'), 
						array($to['Sr'], $to['Name'], $to['Surnames'], $company['Url_Site'], $company['Information_Email'], $company['Owner_Name']), 
						$email_msg
					);
		
		$mail = new Zend_Mail('utf8');
		$mail->addTo($to['Email'], 'Bienvenido a '. $company['Company_Name'])
			->setSubject('Bienvenido a '.  $company['Company_Name'])
			->setBodyHtml($msg)
			->setReplyTo($company['Information_Email'], $company['Information_Name'])
			->setFrom($company['Information_Email'], $company['Information_Name']);
		$sent = true;
		try {
			$mail->send();
		}
		catch (Exception $e){
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
			$sent = false;
		}
		return $sent;
	}


	public function getAllBillingInformationByUserId($id=0){

		$TO = new Default_Model_TO_Users();

		try{
			$sql=$this->getAdapter()
			->select()
			->from(array('bi' =>TABLE_PREFIX.'billing_information'),
					array('bi.Id','bi.Name','bi.Surnames', 'bi.Phone', 'bi.Address1','bi.CP', 'bi.NumExt', 'bi.Col', 'bi.City', 'bi.RFC', 'bi.Used')
			)
			->joinLeft(array('p' => TABLE_PREFIX.'paises'), 'p.Id=bi.Country_Id', array("Pais" => 'p.pais'))
			->joinLeft(array('e' => TABLE_PREFIX.'estados'), 'e.Id=bi.State_Id', array("Estado" => 'e.Estado')
			)->where('bi.User_Id=?', $id);

			$data0 = $this->getAdapter()->fetchAll($sql);
			$rowCount = count($data0);

			if ($rowCount > 0){
				foreach($data0 as $dt){
					$TO->setId($dt['Id']);
					$TO->setName($dt['Name']);
					$TO->setSurnames($dt['Surnames']);
					$TO->setPhone($dt['Phone']);
					$TO->setAddress1($dt['Address1']);
					$TO->setCP($dt['CP']);
					$TO->setNumExt($dt['NumExt']);
					$TO->setCol($dt['Col']);
					$TO->setCity($dt['City']);
					$TO->setRFC($dt['RFC']);
					$TO->setPais($dt['Pais']);
					$TO->setEstado($dt['Estado']);
					$TO->setDefaultUsed($dt['Used']);
					$TO->add();
				}
				$data = $TO->getAllData();
				return $data;
			}
			return null;
		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}

	}
	
/**
 * Obtiene el total de usuarios en la Db
 * */
	public function getTotalUsers(){
		$TO = new Default_Model_TO_Users();
		try{
			$sql=$this->getAdapter()
			->select()
			->from(array('u' => TABLE_PREFIX.'users'),array('Totalusers' => new Zend_Db_Expr('COUNT(u.Id)')))
			->where('u.Role>1');
			
			$data0 = $this->getAdapter()->fetchAll($sql);
			$rowCount = count($data0);
			 
			if ($rowCount > 0){
				foreach ($data0 as $dt){
					$TO->setTotalusers($dt['Totalusers']);
				}
			}
			$data = $TO->getAllVars();
			return $data;
			 
		}catch( Exception $e ) {
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
		return false;
	}
	
/**
 * Agrega los productos de la DB a la sesion del carrito
 * */	
	public function setProductsFromDbToSessionCart($userid=0){
		
		$Session_Cart= new Zend_Session_Namespace('Cart');
		$facadeCart = new Default_Model_Facade_Cart();
		$productsinDb= $this->getProductsByUserId($userid);
		
		try{
			foreach($productsinDb as $cart){
				$To = new Default_Model_TO_Cart();
				$To->setProductId($cart['ProductId']);
				$To->setProductQuantity($cart['ProductQuantity']);
				$facadeCart->addProduct($To->getAllVars());
			}
		}
		catch(Exception $e){
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
		
	}
	
/**
 * Obtiene productos aun en el carro sin pagar de la DB por usuario
 * */	
	public function getProductsByUserId($userid=0){
		$TO = new Default_Model_TO_Cart();
		
		try{
			$sql=$this->getAdapter()
			->select()
			->from(	array('c' =>TABLE_PREFIX.'cart'), array('c.Id'))
			->joinLeft(array('cp' => TABLE_PREFIX.'cart_products'), 'cp.Cart_Id=c.Id', array('cp.Product_Id', 'Product_Qty'))
			->where('c.User_Id=?', $userid)
			->where('c.Status=?', 0);
		
			$data0 = $this->getAdapter()->fetchAll($sql);
			$rowCount = count($data0);
		
			if ($rowCount > 0){
				foreach($data0 as $dt){
					$TO->setProductId($dt['Product_Id']);
					$TO->setProductQuantity($dt['Product_Qty']);
					$TO->add();
				}
				$data = $TO->getAllData();
				return $data;
			}
		
			return true;
		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
		
	}
	
	
	public function IsThisMyPassword($to=array()){
		
		try{
			$_qry=$this->getAdapter()->select()->from(array('u' =>TABLE_PREFIX.'users'), array('u.Id'))
			->where('u.Id=?', $to['UserId'])
			->where('u.Password=?', md5($to['Password']));
		
			$data0 = $this->getAdapter()->fetchOne($_qry);
		
			if ($data0){ return true; }
			return false;
		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
			return false;
		}
	}
	
	public function updatePasswordByUserId($to=array()){
		
		try{
			$where[]="Id=".$to['UserId'];
			$_qry=$this->getAdapter()->update(TABLE_PREFIX.'users', array('Password' => md5($to['NewPassword'])), $where);
		
			return $_qry;
		
		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
			return false;
		}
	}



}


?>